<?php
class News extends CI_Controller
{
	protected $_templates;
	
	public function __construct()
	{
        parent::__construct();
		$this->load->model('news_model','news');
		
		$this->pre_message = "";
		//$this->permit_library->check_permit();
		//$this->session->set_userdata(array('Url'=>uri_string()));
		
		$this->load->helper('search');
		$this->load->helper('img');
		$this->load->helper('date');
		$this->load->library('editor_library');
		$this->lang->load('news');
	}
	
	function index()
	{
		$this->listnews();
	}
  
	// Bengin list news
	function listnews()
	{
        /*Begin search*/
        $type = $this->input->post('type');
       
        $current_router = $this->router->fetch_class();
        if($this->session->userdata('current_router')&&($this->session->userdata('current_router')!=$current_router)){
            $this->session->set_userdata('key_search','');
        }
        $this->session->set_userdata('current_router',$current_router);

        $data['search_bar']= searchBar(array(),array('TT'=>'Title'),'index.php/news/listnews');
        if($type=='ajax')
        {
            $arr_search['key_search'] = $this->input->post('key_search');
            $arr_search['field_search'] = $this->input->post('field_search');
            $this->session->set_userdata('key_search',$arr_search['key_search']);
            $this->session->set_userdata('field_search',$arr_search['field_search']);
        }
        else{
            $arr_search['key_search']=$this->session->userdata('key_search');
            $arr_search['field_search']=$this->session->userdata('field_search');
        }
        /*End  search*/
		$start = (int)$this->uri->segment(4) ;
		$data['title'] = "Danh sách tin tức";
		$data['add'] = 'news/add';
		//$data['trash'] = 'news/trash';
		$config['base_url'] = base_url().'news/listnews/'.(int)$this->uri->segment(3);  
		$data['num'] = $this->news->get_num_news($arr_search);
		$config['total_rows']   =  $data['num'];
		$config['per_page']  =   '20';
		$config['uri_segment'] = 4;   
		$this->pagination->initialize($config);   
		$data['list'] =   $this->news->get_all_news($config['per_page'], $start,$arr_search);
		$data['pagination']    = $this->pagination->create_links();            
		
		$this->_templates['page'] = 'news/news_view';
        if($type=="ajax")
            echo $this->load->view($this->_templates['page'],$data,true);
        else
            $this->site->load($this->_templates['page'],$data);
	}
  
	function add()
	{
		$data['title'] = lang('add_news');
		$data['postcat'] = $this->news->getCatActive();
		
		$this->form_validation->set_rules('lb_title',lang('title'),'trim|required');
		$this->form_validation->set_rules('lb_summary',lang('summary'),'trim|required');
		$this->form_validation->set_rules('lb_content','','');
		if($this->form_validation->run()== FALSE)
		{
			$this->pre_message = validation_errors();
		}
		else
		{
		  $data = $this->build_data($_POST,1);
		  if($this->news->save_news($data))
		  {
			 	$img_news = $this->input->post('lb_image') ;
				if($img_news!='')
				{ 
					if(file_exists('../uploads/news/'.$img_news))
					{
						unlink('../uploads/news/'.$img_news);
					}
				 	fn_resize_image('../uploads/images/'.$img_news,'../uploads/news/'.$img_news,135,110);
				}                     
			  $this->session->set_flashdata('message',lang('save_success'));
			  redirect('index.php/news/listnews');
		  }
		}
		
		$data['message'] = $this->pre_message;
		$this->_templates['page'] = 'news/news_add_view';
		$this->site->load($this->_templates['page'],$data);
	}
  
	function edit()
	{
		$start  = (int) $this->uri->segment(4) ;
		$data['rs'] = $this->news->get_news_item();
		$data['title'] = lang('update').' '.$data['rs']->lb_title;
		$data['postcat'] = $this->news->getCatActive();
		
		$this->form_validation->set_rules('lb_title',lang('title'),'trim|required');
		$this->form_validation->set_rules('lb_summary',lang('summary'),'trim|required');
		$this->form_validation->set_rules('lb_content','','');
		if($this->form_validation->run()== FALSE)
		{
			$this->pre_message = validation_errors();
		}
		else
		{
			$data = $this->build_data(0); 
			if($this->news->save_news($data))
			{
				$img_news = $this->input->post('lb_image') ;
				if($img_news!='')
				{
					if(file_exists('../uploads/news/'.$img_news))
					{
						unlink('../uploads/news/'.$img_news);
					}
				 	fn_resize_image('../uploads/images/'.$img_news,'../uploads/news/'.$img_news,135,110);
				}
				      
				$this->session->set_flashdata('message',lang('save_success'));
				redirect('news/listnews/0/'.$page);
			}
		}
		$data['message'] = $this->pre_message;
		$this->_templates['page'] = 'news/news_edit_view';
		$this->site->load($this->_templates['page'],$data);
	}
  
	function build_data($flag=1)
	{
		//flag=10?insert:update
		$req["lb_title"] = $this->input->post("lb_title");
		$req["lb_image"] = $this->input->post("lb_image");
		$req["lb_summary"] = $this->input->post("lb_summary");
		$req["lb_content"] = $this->input->post("lb_content");
        $req["lb_keyword"] = $this->input->post("lb_keyword");
		$req["category_id"] = $this->input->post("category_id");
		
		$req["dt_create"] = date('Y-m-d H:i:s') ;
		$req["dt_modify"] = date('Y-m-d H:i:s') ;
		$req["bl_active"] = (int) $this->input->post("bl_active") ;
		
		return $req;
	}
	
	function del()
	{
		$id = $this->uri->segment(3);
		$page = $this->uri->segment(4);
		
		//	if($this->news->del_news($id))
		if($this->news->del_updates($id))
			$this->session->set_flashdata('message',lang('delete_success'));
		else $this->session->set_flashdata('message',lang('delete_unsuccess'));
		
		$this->news->remove() ;
		redirect('news/listnews/0/'.$page);
	}
	
	function dels()
	{
		if(!empty($_POST['ar_id']))
		{
			$page = (int)$this->input->post('page');
			$ar_id = $this->input->post('ar_id');
			
			if(!empty($_POST['btn_submit']))
			{
				for($i = 0; $i < sizeof($ar_id); $i ++) {
					if ($ar_id[$i]){
						//del_updates($id)
						if($this->news->del_updates($ar_id[$i]))
						//if($this->news->del_news($ar_id[$i]))
							$this->session->set_flashdata('message',lang('delete_success'));
						else $this->session->set_flashdata('message',lang('delete_unsuccess'));
					}
				}
			}
		}
		redirect('news/listnews/0/'.$page);
	}    
  
 	//tritigi:14.06.2012:lay list tin lein quan
	function related()
	{
	  
	  $data['title'] = lang('list_spotlinght');
	  $data['add'] = 'news/add';
	  $config['base_url'] = base_url().'news/related/'.(int)$this->uri->segment(3);  
	  $data['num'] = $this->news->get_num_news();
	  $config['total_rows']   =  $data['num'];
	  $config['per_page']  =   '20';
	  $config['uri_segment'] = 4;   
	  $this->pagination->initialize($config);   
	  $data['list'] =   $this->news->get_all_news($config['per_page'],(int)$this->uri->segment('4'));
	  $data['pagination']    = $this->pagination->create_links();            
	  $this->_templates['page'] = 'news/news_related';
	  $this->site->load($this->_templates['page'],$data,'basic');
	
	}
	
	//tritigi:14.06.2012:get news title from list newsid
	function get_news_title_from_listid()
	{
		//use when edit, make how to list id is a array
		$mode = isset($_POST['mode']) ? $_POST['mode'] : 0 ; 
		if(empty($mode))
			$list_id = isset($_POST['arr_id']) ? $_POST['arr_id'] : 0 ;
		else
			$list_id = isset($_POST['arr_id']) ? explode(",",$_POST['arr_id']) : 0 ;
		
		$data['list'] = $this->news->get_news_by_listid($list_id);
		
		$this->_templates['page'] = 'news/table_news';
		echo $this->load->view($this->_templates['page'],$data);
	 }
	 
	function trash()
	{
		/*Begin search*/
		$type = $this->input->post('type');
		
		$current_router = $this->router->fetch_class();
		if($this->session->userdata('current_router')&&($this->session->userdata('current_router')!=$current_router)){
		$this->session->set_userdata('key_search','');
		}
		$this->session->set_userdata('current_router',$current_router);
		
		$data['search_bar']=searchBar(array(),array('TT'=>'Title'),'news/listnews');
		if($type=='ajax')
		{
		$arr_search['key_search'] = $this->input->post('key_search');
		$arr_search['field_search'] = $this->input->post('field_search');
		$this->session->set_userdata('key_search',$arr_search['key_search']);
		$this->session->set_userdata('field_search',$arr_search['field_search']);
		}
		else{
		$arr_search['key_search']=$this->session->userdata('key_search');
		$arr_search['field_search']=$this->session->userdata('field_search');
		}
		/*End  search*/
		$start = (int)$this->uri->segment(4) ;
		$data['title'] = lang('list_spotlinght');
		$data['add'] = 'news/add';
		$data['trash'] = 'news/trash';
		$config['base_url'] = base_url().'news/listnews/'.(int)$this->uri->segment(3);  
		$data['num'] = $this->news->get_num_trash($arr_search);
		$config['total_rows']   =  $data['num'];
		$config['per_page']  =   '20';
		$config['uri_segment'] = 4;   
		$this->pagination->initialize($config);   
		$data['list'] =   $this->news->get_all_trash($config['per_page'], $start,$arr_search);
		$data['pagination']    = $this->pagination->create_links();            
		$this->_templates['page'] = 'news/news_trash';
		if($type=="ajax")
		echo $this->load->view($this->_templates['page'],$data,true);
		else
		$this->site->load($this->_templates['page'],$data);
	}
	
	// category
	function category()
	{
          $data['title'] = "Danh mục tin tức";
          $data['add'] = 'news/addcat';
          $config['base_url'] = base_url().'index.php/news/category/';  
          $config['total_rows']   =  $this->news->getNumcat();
          $data['num'] = $config['total_rows'];
          $config['per_page']  =   20;
          $config['uri_segment'] = 3; 
          $this->pagination->initialize($config);   
          $data['list'] =   $this->news->getAllCat($config['per_page'],$this->uri->segment('3'));
          $data['pagination']    = $this->pagination->create_links(); 
          $this->_templates['page'] = 'news/cat/index';
          $this->site->load($this->_templates['page'],$data);         
      }
	  
      function addcat()
	  {
          $data['title'] = 'Thêm mới chuyên mục';
          $data['listcat'] = $this->news->get_Parent(0);
          if(!empty($_POST['bt_submit'])){
                $this->form_validation->set_rules('lb_category','Tên chủ đề','trim|required');
         
                if($this->form_validation->run() == FALSE){
                    $this->pre_message = validation_errors();
                }else{
                    if($this->news->saveUpdateCat()){
                    $this->session->set_flashdata('message','Thêm mới chuyên mục thành công');
                    redirect('news');
                }
             }
          }       
          $this->_templates['page'] = 'news/cat/addcat';
          $this->site->load($this->_templates['page'],$data);           
      }
      
      function editcat()
	  {                                          
          $data['rs'] = $this->news->getItemCat();
          $data['title'] = 'Cập nhật: '.$data['rs']->lb_category;
          $data['listcat'] = $this->news->get_Parent(0);
          if(!empty($_POST['bt_submit'])){
                $this->form_validation->set_rules('lb_category','Tên chủ đề','trim|required');
       
                if($this->form_validation->run() == FALSE){
                    $this->pre_message = validation_errors();
                }else{
                    if($this->news->saveUpdateCat()){
                    $this->session->set_flashdata('message','Cập nhật chuyên mục thành công');
                    redirect('news/category');
                }
             }
          }  
          $this->_templates['page'] = 'news/cat/editcat';
          $this->site->load($this->_templates['page'],$data);
      }
	  
      function delcat()
	  {
          $id = $this->uri->segment(3);
          $page = $this->uri->segment(4);
            if($this->news->delcat($id))
                $this->session->set_flashdata('mesasge','Đã xóa thành công');
            else $this->session->set_flashdata('mesasge','Xóa không thành công');
          redirect('news/category/'.$page);
      }
      
      function delscat()
      {
            if(!empty($_POST['ar_id']))
            {
                $page = (int)$this->input->post('page');
                $ar_id = $this->input->post('ar_id');
                
                if(!empty($_POST['btn_submit']))
                {
                    for($i = 0; $i < sizeof($ar_id); $i ++) {
                        if ($ar_id[$i]){
                            if($this->news->delcat($ar_id[$i]))
                                $this->session->set_flashdata('mesasge','Đã xóa thành công');
                            else $this->session->set_flashdata('mesasge','Xóa không thành công');
                        }
                    }
                }
            }
            redirect('index.php/news/category/'.$page);
      }
}
?>
